package com.loren.demo03.tcp2.protocol;

import io.netty.buffer.ByteBuf;

import java.nio.charset.StandardCharsets;

public class MsgProtocol {

    /**
     * 数据头部标识
     */
    public static final byte DATA_HEAD = 0x58;

    /**
     * 数据尾部标识
     */
    public static final byte DATA_TAIL = 0x63;

    /**
     * 最小的数据长度：开头占1字节，数据内容长度int占4字节，结尾占1字节
     */
    public static final int DATA_MIN_LENGTH = 6;

    /**
     * 数据内容
     */
    private final byte[] content;

    public MsgProtocol(String content) {
        this.content = (content != null ? content : "").getBytes(StandardCharsets.UTF_8);
    }

    public byte[] getContent() {
        return content;
    }

    public int getLength() {
        return this.content.length;
    }

    public void write(ByteBuf byteBuf) {
        byteBuf.writeByte(DATA_HEAD);
        byteBuf.writeInt(this.getLength());
        byteBuf.writeBytes(this.getContent());
        byteBuf.writeByte(DATA_TAIL);
    }
}
